package com.ldodds.ot.property.jena;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.hp.hpl.jena.shared.PrefixMapping;
import com.ldodds.ot.property.AbstractPropertyMapper;

/**
 * Implementaton of the {@link com.ldodds.ot.property.PropertyMapper} interface 
 * that supports mapping predicates to URIs using the prefix mapping configuration 
 * associated with a specific Jena Model.
 * <p>
 * In the Jena API a <code>PrefixMapping</code> instance holds references between 
 * namespace prefixes and namespace URIs. These are typically populated automatically 
 * when parsing an RDF file, or from the <code>PREFIX</code> declarations in a SPARQL 
 * query. This implementation of the {@link com.ldodds.ot.property.PropertyMapper} 
 * interface reuses that configuration to generate the simple keys used to annotate
 * {@link com.ldodds.ot.PropertyHolder} instances.
 * </p>
 * @author Leigh Dodds
 */
public class PrefixMappingPropertyMapper extends AbstractPropertyMapper
{
	private Map<String,String> prefixes;
	private String separator;

	/**
	 * Construct the property mapper using an existing prefix mapping instance
	 * @param prefixMapping
	 */
	public PrefixMappingPropertyMapper(PrefixMapping prefixMapping) {
		this(prefixMapping, DEFAULT_SEPARATOR);
	}

	/**
	 * Construct the property mapper using an existing prefix mapping instance, 
	 * and specifying the separator to be used when concatenating the prefix 
	 * with the suffix of the predicate URI. 
	 * @param prefixMapping
	 * @param separator
	 */
	public PrefixMappingPropertyMapper(PrefixMapping prefixMapping, 
			String separator) {
		this.prefixes = remap( prefixMapping.getNsPrefixMap() );
		this.separator = separator;
	}

	protected String mapURI(String propertyURI) {
		return null;
	}

	protected String mapBaseURI(String baseURI) {
		return prefixes.get(baseURI);
	}	
	
	protected String getSeparator() {
		return separator;
	}
	
	private Map<String, String> remap(Map prefixMap) {
		Map<String, String> prefixes = new HashMap<String,String>();
		
		for (Iterator iter = prefixMap.entrySet().iterator(); iter.hasNext(); ) {
			Map.Entry entry = (Map.Entry)iter.next();
			prefixes.put( entry.getValue().toString(), entry.getKey().toString() );
		}
		return prefixes;
	}
}
